package reflect;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Scanner;

/**
 * 利用反射机制调用方法
 * @author XingHaiYang
 * @date 2022/9/16 10:40
 */
public class ReflectDemo4 {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入类名:");
        String className = scanner.nextLine();
        System.out.println("请输入方法名:");
        String methodName = scanner.nextLine();
        Class cls = Class.forName(className);//获取类对象
        Object obj = cls.newInstance();//获取对象实例
        Method method = cls.getMethod(methodName);//获取指定方法
        method.invoke(obj);//执行方法，相当于调用对象的方法执行
    }
}
